package cn.szzsi.service;

import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.model.Product;
import cn.szzsi.common.model.ProductCategory;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Service实现类 - 生成静态
 *
 */
public class ProductService {

	public static final ProductService service = new ProductService();
	private List<Product> products;//全部商品

	/**
	 * 根据产品的规格系列获取同批次所有的规格
	 * @param product
	 * @return
	 */
	public List<String> getAllProductSpecificationType(Product product){
		List<String> ss = null;
		if(product!=null && StrKit.notBlank(product.getStr("specificationtype"))){
			List<Record> list = Db.find("select specificationvalues,specificationids,id,price,store from mall_product where specificationtype = ?",product.getStr("specificationtype"));
			if(list != null && list.size()>0){
				ss = new ArrayList<String>();
				for(Record r:list){
					ss.add(r.getStr("id")+"@"+r.getStr("specificationvalues")+","+r.getStr("specificationids")+"$"+r.getBigDecimal("price")+"#"+r.getInt("store"));
				}
			}
		}
		return ss;
	}

	public void deleteWithSpecificationType(String specificationType){
		Db.update("delete from mall_product where specificationtype = ?",specificationType);
	}


	/**
	 * 保存产品和规格的方法
	 * @param product
	 * @param req
	 * @param uid
	 * @param userId 添加人
	 */
	public void saveOrUpdateProductWithSpecification(Product product, HttpServletRequest req, String uid, String userId){
		Boolean isShow = product.getIsShowSku();
		String[] specificationIds = req.getParameterValues("specificationIds");
		if(specificationIds != null && specificationIds.length > 0){
			List<String> list = this.getSpecification(req,specificationIds);

			String tmpid = "";//传过来的产品id
			String tmpval = "";//规格值
			String typeid = CommonUtil.getUUID();
			BigDecimal tmpPrice = product.getPrice();
			Integer store = product.getStore();
			Boolean isShowSku = product.getIsShowSku();
			//如果设置部分sku显示，则默认显示当前产品，如果设置分sku显示，则当前产品需要修改为显示
			if (!isShowSku){
				product.setDisplay(!isShowSku);
			}else {
				product.setDisplay(isShowSku);
			}
			Integer index = 1;
			for(String s:list){
				//库存
				if (StringUtils.contains(s,"#")) {
					//String storeStr = StringUtils.substringAfter(s,"#");
					if (StringUtils.contains(s, "#")) {
						if (StringUtils.isNotBlank(StringUtils.substringAfter(s, "#"))){
							store = Integer.parseInt(StringUtils.substringAfter(s, "#"));
							product.setStore(store);
						}
					}
					s = StringUtils.substringBefore(s,"#");
				}
				//价格
				if (StringUtils.contains(s,"$")) {
					if (StringUtils.isNotBlank(StringUtils.substringAfter(s, "$"))){
						tmpPrice = new BigDecimal(StringUtils.substringAfter(s, "$"));
						product.setPrice(tmpPrice);
					}
					s = StringUtils.substringBefore(s,"$");
				}
				if(StringUtils.contains(s,"@")){//
					tmpval = StringUtils.substringBefore(s,",@");
					tmpid =  StringUtils.substringAfter(s,",@");

					if(tmpid.equalsIgnoreCase("NONE")){//修改中的新增
						product.setDisplay(false);
						product.set("specificationids", StringUtils.join(specificationIds,",")).set("specificationvalues",tmpval).set("specificationtype",typeid);
						Product.dao.save(product,uid,"save",userId);
					}else if(product.getId().equals(tmpid)){//修改当前商品
						product.set("specificationids",StringUtils.join(specificationIds,",")).set("specificationvalues",tmpval).set("specificationtype",typeid);
						//TODO
                        Product.dao.save(product,uid,"update",userId);
					}else{//修改其他商品sku
						Product p = Product.dao.findById(tmpid);
						//修改其他商品，则显示规则按照设置显示
						p.setIsShowSku(product.getIsShowSku());
						p.setDisplay(product.getIsShowSku());
						p.setStore(store);
						p.setPrice(tmpPrice);
						p.set("specificationids",StringUtils.join(specificationIds,",")).set("specificationvalues",tmpval).set("specificationtype",typeid);
						//TODO
						Product.dao.save(p,uid,"update",userId);
					}
				}else{//纯新增的情况
					//如果是不分sku，则指定一个商品显示，如果是分sku,则所有display都是1
					if (!isShowSku){
						if (index > 1) {
							product.setDisplay(false);
						}else {
							product.setDisplay(true);
						}
					}else {
						product.setDisplay(true);
					}
					index ++;
					product.set("specificationids",StringUtils.join(specificationIds,",")).set("specificationvalues",s).set("specificationtype",typeid);
					Product.dao.save(product,uid,"save",userId);
				}
			}
		}else{
			//没有设置商品规格
			String typeid = CommonUtil.getUUID();
			product.setSpecificationtype(typeid);
            if(StrKit.isBlank(product.getStr("id"))) {
				product.save(product, uid, "save",userId);
			} else {
				product.save(product, uid, "update",userId);
			}
		}
		//更新最小价格的sku为主显示sku
		if (StringUtils.isNotBlank(product.getSpecificationtype())) {
			if (!isShow) {
				Db.update("update mall_product set isShowSku=0, display=0 where specificationtype=?", product.getSpecificationtype());
				Product tmp = Product.dao.findFirst("select * from mall_product where specificationtype=? ORDER BY price asc", product.getSpecificationtype());
				tmp.setDisplay(true);
				tmp.update();
			}else {
				Db.update("update mall_product set isShowSku=1, display=1 where specificationtype=?", product.getSpecificationtype());
			}
		}
	}

	/**
	 * 获取用户端的规格参数
	 * @param req
	 * @param values
	 * @return
	 */
	public List<String> getSpecification(HttpServletRequest req, String[] values){
		//有规格的设置
		//先判断有多少规格产品
		int row = req.getParameterValues("specification_"+values[0]).length;
		List<String> list = new ArrayList<String>();

		try {
			if(values!=null && values.length >0){
				String[] specificationProductIds = req.getParameterValues("specificationProductIds");
				String[] specificationPrice = req.getParameterValues("specificationPrice");
				String[] specificationStore = req.getParameterValues("specificationStore");
				for(int i=0;i<row;i++){
					String tmp = "";
					for(int j=0;j<values.length;j++){
						tmp += req.getParameterValues("specification_"+values[j])[i]+",";
					}

					if(specificationProductIds != null && specificationProductIds.length>0){
						if(specificationProductIds.length > i){
							tmp += "@"+specificationProductIds[i];
						}else{
							tmp += "@NONE";
						}
					}
					//价格
					if (specificationPrice != null && specificationPrice.length > 0) {
						if ((specificationPrice.length) > i) {
							tmp +="$"+specificationPrice[i];
						}else {
							tmp+="$NOPICE";
						}
					}
					//库存
					if (specificationStore != null && specificationStore.length > 0) {
						if ((specificationStore.length) > i) {
							tmp +="#"+specificationStore[i];
						}else {
							tmp+="#NOSTORE";
						}
					}

					list.add(tmp);
				}
			}
		}catch (Exception e){

		}

		return list;
	}

	//根据关键字返回商品集合
	public Page<Product> getByKeyword(Integer pageNumber, Integer pageSize, String uid, String columm, String sortType, String keyword){
		StringBuilder sql=new StringBuilder("from mall_product where uid='"+uid+"' and ismarketable=true and display=1 and checked='1' and name like '%"+keyword+"%' order by "+columm+" "+sortType+"");
		Page<Product> pager = Product.dao.paginate(pageNumber,pageSize,"select * ",sql.toString());
		return pager;
	}
	//根据关键字返回商品集合
	public Page<Product> getByKeywordPlateForm(Integer pageNumber, Integer pageSize,String columm, String sortType, String keyword){
		StringBuilder sql=new StringBuilder("from mall_product where ismarketable=true and display=1 and checked='1' and name like '%"+keyword+"%' order by "+columm+" "+sortType+"");
		Page<Product> pager = Product.dao.paginate(pageNumber,pageSize,"select * ",sql.toString());
		return pager;
	}

	//根据商品分类返回商品集合
	public Page<Product> getRootProductCategory(Integer pageNumber, Integer pageSize, ProductCategory productCategory, String column, String sortType){
		String sqlExceptSelect =""
				+" from mall_product p "
				+" left join mall_product_category c "
				+"   on p.productcategory_id = c.id "
				+" where (p.productcategory_id = '"+productCategory.getStr("id")+"' or c.path like '"+productCategory.getStr("path")+ "%"+"') "
				+"  and p.ismarketable = true and p.display=1 and checked='1'";
		sqlExceptSelect += " order by " + column +" "+ sortType;
		StringBuilder sql=new StringBuilder(sqlExceptSelect);
		Page<Product> pager = Product.dao.paginate(pageNumber,pageSize,"select p.*",sql.toString());
		return pager;
	}

	public Page<Product> getByUid(Integer pageNumber, Integer pageSize, String uid, String column, String sortType){
		StringBuilder sql=new StringBuilder("from mall_product where uid='"+uid+"' and ismarketable=true and display=1 and checked='1' order by "+column+" "+sortType+"");
		Page<Product> pager = Product.dao.paginate(pageNumber,pageSize,"select * ",sql.toString());
		return pager;
	}

	public Page<Product> getAll(Integer pageNumber, Integer pageSize, String column, String sortType){
		StringBuilder sql=new StringBuilder("from mall_product where ismarketable=true and display=1 and checked='1' order by "+column+" "+sortType+"");
		Page<Product> pager = Product.dao.paginate(pageNumber,pageSize,"select * ",sql.toString());
		return pager;
	}



}
